package com.xer.zip;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;


public class Decomprimir {
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Map<String,String> map = filesToDecompress();
		
		if(!map.isEmpty()){
			Iterator<String> i = map.keySet().iterator();
				while(i.hasNext()){
					  String name = i.next();
					  unCompress(map.get(name) ,name);	
				}	
		}
	}
	
	
	private static Map<String,String>  filesToDecompress(){
	
		Map<String,String> map = new HashMap<String,String>();
		String path;
		String file;
		
		path = "/home/xer/Escritorio/comprimido";
		file= "/home/xer/Escritorio/db 2014-02-14T01:00:22";
		map.put(path, file);
		
		path = "/home/xer/Escritorio/comprimido2";
		file= "/home/xer/Escritorio/db1 2014-02-14T01:00:22";
		map.put(path, file);
		
		return map;
		
	}
	
	private static void prepareFileDirectories (String destination,String entryName){
		//si no existe el directorio lo creo
		File f = new File(destination);
		if( !f.exists()){
			f.mkdirs();
		}
		
	}
	private static void unCompress(String filename, String destination) {
		int BUFFER_SIZE = 8192;
		try {
			// Create a ZipInputStream to read the zip file
			BufferedOutputStream dest = null;
			FileInputStream fis = new FileInputStream(filename);
			ZipInputStream zis = new ZipInputStream(
			
			new BufferedInputStream(fis));
			// Loop over all of the entries in the zip file
			int count;
			byte data[] = new byte[BUFFER_SIZE];
			ZipEntry entry;
			while ((entry = zis.getNextEntry()) != null) {
				if (!entry.isDirectory()) {
					String entryName = entry.getName();
					prepareFileDirectories(destination, entryName);
					/*
					 String destFN = destination + File.separator
							+ entry.getName();
					*/
					String fileName =entry.getName();
					if(entry.getName().lastIndexOf(File.separator)!=-1){
						fileName =entry.getName().substring(entry.getName().lastIndexOf(File.separator));
					}
					 String destFN =destination + fileName;
					// Write the file to the file system
					FileOutputStream fos = new FileOutputStream(destFN);
					dest = new BufferedOutputStream(fos, BUFFER_SIZE);
					while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
						dest.write(data, 0, count);
					}
					dest.flush();
					dest.close();
				}
			}
			zis.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
